<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

      <div style="margin-top: 15px;margin-bottom: 15px;">
       <el-button type="primary" v-if="this.actions.includes('2')" icon="HMS el-icon-addRole" @click="openAddDiog()">添加角色</el-button>
    </div>
    <el-card>
      <el-table :data="this.userList.data" border stripe @expand-change="expand" :expand-row-keys="expands" :row-key="getRowKeys">
        <el-table-column  type="expand" align="center">
            <template slot-scope="scope">
                <el-row :class="['tagBottom', i1 === 0 ? 'tagTop' : '']" v-for="(item, i1) in scope.row.menuList" :key="item.id" >
                    <el-col :span="5">
                        <el-tag v-if="actions.includes('3')" type="danger" :disable-transitions="false" closable @close="handleClose3(scope.row,item.id,-1)">{{ item.menuTitle }}</el-tag>
                        <el-tag v-if="!actions.includes('3')" type="danger" :disable-transitions="false" >{{ item.menuTitle }}</el-tag>
                        <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="19">
                        <el-row :class="[ i2 !== 0 ? 'tagTop' : '']" v-for="(item2, i2) in item.children" :key="item2.menuId">
                            <el-col :span="5">
                                <el-tag v-if="actions.includes('3')" type="success" :disable-transitions="false" closable @close="handleClose3(scope.row,item2.id,0)" >{{ item2.menuTitle }}</el-tag>
                                <el-tag v-if="!actions.includes('3')" type="success" :disable-transitions="false" >{{ item2.menuTitle }}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col v-if="actions.includes('3')" :span="14">
                                <el-tag :disable-transitions="false" v-for="(item3, i3) in item2.children" :key="i3" type="warning" closable @close="handleClose3(scope.row,item2.id,item3.id)" >{{ item3.menuTitle }}</el-tag>
                            </el-col>
                               <el-col v-if="!actions.includes('3')" :span="14">
                                <el-tag :disable-transitions="false" v-for="(item3, i3) in item2.children" :key="i3" type="warning" >{{ item3.menuTitle }}</el-tag>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
                <el-button v-if="actions.includes('3')" class="button-new-tag" size="small" @click="showInput(scope.row.menuList, scope.row.roleId)">+ 新增菜单权限</el-button>
          </template>
          </el-table-column>
        <el-table-column type="index" align="center">
        </el-table-column>
        <el-table-column label="角色名" prop="roleName" align="center">
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center"></el-table-column>
        <el-table-column v-if="this.actions.includes('3') || this.actions.includes('4')" label="操作" prop="username" align="center">
          <template slot-scope="scope">
            <el-button v-if="actions.includes('3')"  type="primary" icon="el-icon-edit" @click="openDiog(scope.row)"></el-button>
            <el-button v-if="actions.includes('4')" type="danger" @click="delRole(scope.row.roleId)" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.page"
        :page-sizes="[1, 2, 5, 10, 20]"
        :page-size="this.queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.totalNum"
      ></el-pagination>
    </el-card>
    <!-- 修改角色 -->
    <el-dialog title="角色修改" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="updateForm" :rules="addRoleRule" ref="updateFormRef" label-width="70px" autocomplete="off">
        <el-form-item prop="remark" label="姓名">
          <el-input v-model="updateForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm()">取 消</el-button>
        <el-button type="primary" @click="updateRole()">修 改</el-button>
      </div>
    </el-dialog>
        <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addRoleFormVisible" width="30%">
      <el-form :model="addForm" :rules="addRoleRule" ref="addFormRef" label-width="70px" autocomplete="off">
        <el-form-item prop="roleName" label="角色名">
          <el-input v-model="addForm.roleName" placeholder="角色名提交后不可更改"></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="addForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole()">确 认</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog
    :center="true"
  title="权限分配"
  :visible.sync="dialogMenuVisible"
  width="20%" @close="closeRoleRight()">
  <!-- 树型组件 -->
  <el-tree :data="this.menuList" show-checkbox node-key="id"
  default-expand-all
  :default-checked-keys="selectedIds"
  :props="menuListProps" ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogMenuVisible = false">取 消</el-button>
    <el-button type="primary" @click="changeRoleRight()">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
import { isNumAndAlp } from '@/utils/validate'
export default {
   data () {
          var checkRoleName = (rule,value,callback) => {
         if(!value){
         return callback(new Error('不能为空'));
       }
       if(value.length > 16){
         return callback(new Error('角色名不能超过10位'));
       }
        if(!isNumAndAlp(value)){
           return callback(new Error('角色名只能是字母和数字'));
        }
        callback();
      }
    return {
      // 该页面的操作权限
      actions: this.$store.getters.actions['/roleList'],
      userList: {},
      queryInfo: {
        page: 1,
        limit: 20
      },
      updateRoleRightInfo: {
        roleId: '',
        menuAndAction: []
      },
      totalNum: 100,
      dialogFormVisible: false,
      dialogMenuVisible: false,
      addRoleFormVisible: false,
      updateForm: {},
      menuList: [],
      menuListProps: {
        label: 'menuTitle',
        children: 'children'
      },
      addForm: {},
      addRoleRule: {
        roleName: [{ required: true, trigger: 'blur', validator: checkRoleName }],
        remark: [{ required: true, trigger: 'blur', message: '备注不能为空' },
                  {min: 1, max: 10, message: '长度不合法', trigger: 'blur'}],
      },
      selectedIds: [],
      // 获取row的key值
      getRowKeys (row) {
        return row.roleId
      },
      // 要展开的行，数值的元素是row的key值
      expands: [1]
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    getRoleList () {
      this.$api.role.getRoleList(this.queryInfo).then(res => {
        this.userList = res.data
        this.totalNum = res.data.count
      })
    },
    handleSizeChange (newSize) {
      this.queryInfo.limit = newSize
      this.getRoleList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.page = newPage
      this.getRoleList()
    },
    openDiog (data) {
      this.updateForm = data
      this.dialogFormVisible = !this.dialogFormVisible
    },
    async expand (row, expandedRows) {
    },
    delMenu (k1, k2, k3) {
      this.$api.role.delMenu({
        roleId: k1.roleId,
        menuId: k2,
        actionId: k3
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功')
        }
        this.getRoleList()
      })
    },
    handleClose3 (k1, k2, k3) {
      this.$confirm('是否删除角色该权限 ?', '删除提示', {
        confirmButtonText: '果断删除',
        cancelButtonText: '我再想想',
        type: 'warning'
      }).then(() => {
        this.delMenu(k1, k2, k3)
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    getSelected (data) {
      // 将该角色拥有的权限推入已选数组
      data.forEach(element => {
        if (!element.children) {
          this.selectedIds.push(element.id)
        } else {
          // console.log(element)
          this.getSelected(element.children)
        }
      })
    },
    closeRoleRight () {
      this.selectedIds = []
      this.menuList = []
    },
    showInput (data, id) {
      this.updateRoleRightInfo.roleId = id
      this.dialogMenuVisible = !this.dialogMenuVisible
      this.menuList = this.$store.getters.menuList
      if (data !== null) {
        this.getSelected(data)
      }
    },
    changeRoleRight () {
      const tree = this.$refs.treeRef.getCheckedKeys()
      this.updateRoleRightInfo.menuAndAction = tree
      this.$api.role.updateMenu(this.updateRoleRightInfo).then(res => {
        if (res.code === 200) {
          this.dialogMenuVisible = !this.dialogMenuVisible
          this.$message.success('更新成功')
          this.getRoleList()
        }
      })
    },
    updateRole () {
      this.$refs.updateFormRef.validate(res => {
        if(res){
         this.$api.role.updateRole(this.updateForm).then(res => {
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getRoleList()
          this.dialogFormVisible = !this.dialogFormVisible
        }
      })
        }
      })
    },
    resetForm () {
      this.dialogFormVisible = !this.dialogFormVisible
      // this.getRoleList()
    },
    openAddDiog () {
      this.addForm = {}
      this.addRoleFormVisible = !this.addRoleFormVisible
      this.$refs.addFormRef.resetFields()
    },
    addRole () {
      this.$refs.addFormRef.validate(res => {
        if(res){
        this.$api.role.updateRole(this.addForm).then(res => {
        if (res.code === 200) {
          this.$message.success('添加成功')
          this.getRoleList()
          this.addRoleFormVisible = !this.addRoleFormVisible
        }
      })
        }
      })
    },
    delRole (id) {
          this.$api.role.delRole(id).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功')
          this.getRoleList()
        }else{
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.tagTop {
    border-top: 1px solid #eee;
}

.tagBottom {
    border-bottom: 1px solid #eee;
}
 .button-new-tag {
   margin-top: 10px;
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
